// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/common/memory/memory_arbitrator.h>

namespace kumo::pollux::exec {
    /// Provides the default leaf memory reclaimer implementation for pollux task
    /// execution.
    class MemoryReclaimer : public memory::MemoryReclaimer {
    public:
        virtual ~MemoryReclaimer() = default;

        static std::unique_ptr<memory::MemoryReclaimer> create(int32_t priority = 0);

        void enterArbitration() override;

        void leaveArbitration() noexcept override;

        void abort(memory::MemoryPool *pool, const std::exception_ptr &error)
        override;

    protected:
        explicit MemoryReclaimer(int32_t priortity);
    };

    /// Provides the parallel memory reclaimer implementation for pollux task
    /// execution. It parallelize the memory reclamation from all its child memory
    /// pools.
    class ParallelMemoryReclaimer : public memory::MemoryReclaimer {
    public:
        virtual ~ParallelMemoryReclaimer() = default;

        static std::unique_ptr<memory::MemoryReclaimer> create(
            melon::Executor *executor,
            int32_t priority = 0);

        uint64_t reclaim(
            memory::MemoryPool *pool,
            uint64_t targetBytes,
            uint64_t maxWaitMs,
            Stats &stats) override;

    protected:
        ParallelMemoryReclaimer(melon::Executor *executor, int32_t priority);

        melon::Executor *const executor_{nullptr};
    };

    /// Callback used by memory arbitration to check if a driver thread under memory
    /// arbitration has been put in suspension state. This is to prevent arbitration
    /// deadlock as the arbitrator might reclaim memory from the task of the driver
    /// thread which is under arbitration. The task reclaim needs to wait for the
    /// drivers to go off thread. A suspended driver thread is not counted as
    /// running.
    void memoryArbitrationStateCheck(memory::MemoryPool &pool);
} // namespace kumo::pollux::exec
